package com.lyl.security.controller;

import cn.hutool.core.util.IdUtil;
import com.lyl.common.exception.BizException;
import com.lyl.security.dto.LoginDetails;
import com.lyl.security.dto.UserDTO;
import com.lyl.security.utils.JwtUtil;
import com.lyl.security.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author Mr.Luo
 * @date 2022-09-19 17:35
 * @desc
 */
@RestController
@RequiredArgsConstructor
public class LoginController {
    private final AuthenticationManager authenticationManager;

    /**
     * 登录
     *
     * @param dto 请求参数
     * @return token
     */
    @PostMapping("/login")
    public String login(@RequestBody @Valid UserDTO dto) {
        Authentication authenticate;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword());
            authenticate = authenticationManager.authenticate(authenticationToken);
        } catch (BadCredentialsException e) {
            throw new BizException("用户名密码错误");
        } catch (AuthenticationException e) {
            throw new BizException(e.getMessage());
        }
        LoginDetails loginDetails = (LoginDetails) authenticate.getPrincipal();
        loginDetails.setToken(IdUtil.fastUUID());
        RedisUtil.set("login_token:" + loginDetails.getToken(), loginDetails);
        return JwtUtil.createToken(loginDetails.getToken());
    }
}
